from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from drf_haystack.viewsets import HaystackViewSet

from goods.models import SKU
from users import constants
from .models import User, Address
from .serializers import UserModelSerializer, UserDetailSerializer,\
    EmailSerializer, UserAddressSerializer, AddressTitleSerializer, AddUserBrowsingHistorySerializer
from goods.serializer import SKUListSerializer, SKUIndexSerializer


class SKUSearchViewSet(HaystackViewSet):
    """SKU搜索"""
    index_models = [SKU]
    serializer_class = SKUIndexSerializer


class UserBrowsingHistoryView(CreateAPIView):
    """用户浏览历史记录"""
    serializer_class = AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """获取用户浏览记录"""
        # 从redis取出当前登陆用户的浏览记录redis数据
        redis_conn = get_redis_connection('history')
        sku_ids = redis_conn.lrange('history_%s' % request.user.id, 0, -1)

        sku_list = []
        # 把sku_id对象的SKU模型取出来
        for sku_id in sku_ids:
            sku_model = SKU.objects.get(id=sku_id)
            sku_list.append(sku_model)

        # 进行序列化输出
        serializer = SKUListSerializer(sku_list, many=True)
        return Response(serializer.data)


class AddressViewSet(UpdateModelMixin, CreateModelMixin, GenericViewSet):
    """收货地址"""

    # 指定序列化器
    serializer_class = UserAddressSerializer
    # 指定权限
    # permission_classes = [IsAuthenticated]
    permissions = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request):
        """获取用户地址列表"""
        # 不用mixins的原因是想要返回指定的字段
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    def create(self, request, *args, **kwargs):
        """新增收货地址"""
        count = Address.objects.filter(user_id=request.user.id).count()
        # count = request.user.addresses.count()
        if count > constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)
        # serializer = self.get_serializer(data=request.data)
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        # return Response(serializer.data, status=status.HTTP_201_CREATED)
        return super().create(request, *args, **kwargs)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):  # 这里一定要加 *args, **kwargs 参数
        """处理删除"""
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        :param request:
        :param pk:
        :return:
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()

        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """修改标题"""
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data)


class VerifyEmailView(APIView):
    """
    邮箱验证
    """
    def get(self, request):
        """获取token"""

        # 1.提取token
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)
        # 2.把token解密并取到要修改邮箱状态的user
        user = User.check_verify_email_token(token)
        if not user:
            return Response({'message': '无效的token'})
        user.email_active = True

        user.save()
        return Response({"message": 'OK'})


class EmailView(UpdateAPIView):
    """保存用户邮箱"""
    permission_classes = [IsAuthenticated]
    # 指定序列化器
    serializer_class = EmailSerializer

    def get_object(self):
        return self.request.user


class UserDetailView(RetrieveAPIView):
    """用户详情"""

    serializer_class = UserDetailSerializer  # 指定序列化器
    permission_classes = [IsAuthenticated]  # 限定只有登陆用户才能访问详情

    def get_object(self):
        """
        get_object是默认调用的   现在重写  因为没有视图集 get_object()方法根据pk参数查找queryset中的数据对象
        父类方法中mixins获取对象， 所以需要重写
        :return:
        """
        return self.request.user  # 请求头里面带有user对象属性


class UserView(CreateAPIView):

    # 指定序列化器
    serializer_class = UserModelSerializer


class UsernameCountView(APIView):
    """判断用户是否已经存在"""

    def get(self, request, username):

        # # 拿前端传过来的用户名去查询数据,如果用户已存在count是1 ,否则是0
        count = User.objects.filter(username=username).count()
        data = {
            'username': username,
            'count': count
        }
        return Response(data)


class MobileCountView(APIView):

    def get(self, request, mobile):

        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count
        }

        return Response(data)


